<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="10"><div class="grid-content bg-purple">
        <div class="developer left">
          <div id="box">
            <ul>
              <li v-for="(v, index) in districtList" :key="index">
                <div class="product-content1">
                  <image-preview :src="v.image" alt="Dynamic Image" class="fixed-image-size"/>
                  <div class="info">
                    <h2>{{ v.communityName }}</h2>
                    <h4>{{v.centerPoint}}</h4>
                    <h4>辖区：{{ v.name }}</h4>
                  </div>
                  <div class="additional-info1">
                    <p @click="handlePopulationClick(v.id)">实有人口：{{ v.populationNum }}</p>
                    <p @click="handleEstateClick(v.id)">实有房屋：{{ v.realEstateNum }}</p>
                    <p @click="handleUnitClick(v.id)">实有单位：{{ v.unitNum }}</p>
                    <p @click="handleVehiclesClick(v.id)">实有车辆：{{ v.vehicleNum }}</p>
                    <p @click="handleCacheClick(v.id)">实有力量：{{ v.buildingCount }}</p>
                    <p @click="handleFacilitiesClick(v.id)">实有设备：{{ v.securityFacilitiesNum }}</p>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div></el-col>
<!--      <el-col :span="10"><div class="grid-content bg-purple">

      </div></el-col>-->
      <el-col :span="10"><div class="grid-content bg-purple">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车主" prop="populationId">
        <el-select v-model="queryParams.idCardNumber" :clearable="true" placeholder="请选择车主">
          <el-option
            v-for="item in options"
            :key="item.idCardNumber"
            :label="item.name"
            :value="item.idCardNumber"
            clearable
            @keyup.enter.native="handleQuery">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['community:vehicles:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"

          @click="handleUpdate"
          v-hasPermi="['community:vehicles:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"

          @click="handleDelete"
          v-hasPermi="['community:vehicles:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['community:vehicles:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <label class="el-button el-button--mini el-button--plain" style="cursor: pointer;">
          <input type="file" style="display: none;" @change="handleImport">
          <i class="el-icon-plus"></i> 导入
        </label>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

        <div id="box">
          <ul class="population-list">
            <li v-for="(v, index) in vehiclesList" :key="index" class="product-item">
              <div class="product-content2">
                <input type="checkbox" v-model="selectedItems" :value="v.id" class="checkbox-item" @change="handleSelectionChange(v.id)" />
                <div class="image-container" @click="redirectToVechiclesPage(v)">
                <image-preview :src="v.image" alt="Dynamic Image" class="fixed-image-size1"/>
                </div>
                <br>
                <div class="info">
                  <h4>车牌号：{{v.licensePlate}}</h4>
                  <h4>车主：{{ v.name }}</h4>
                  <h4>性别：{{ v.sex }}</h4>
                  <h4>创建时间：{{ v.createDate }}</h4>
                  <h4>车主身份证：{{ v.idCardNumber }}</h4>
                  <h4>住址：{{ v.residenceAddress }}</h4>
                  <h4>车主电话：{{ v.iphone }}</h4>
                  <h4>所属小区：{{ v.communityName }}</h4>
                  <el-button type="primary" plain size="mini"  @click="redirectToVechiclesPage(v)">一车一档</el-button>
                  <el-button type="primary" plain size="mini" @click="handleControl(v)">一键布控</el-button>
                </div>
              </div>
            </li>
          </ul>
        </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      </div></el-col>
    </el-row>
    <!-- 添加或修改实有车辆信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>
<!--        <el-form-item label="创建时间" prop="createDate">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.createDate"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择创建时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="车辆照片" prop="image">
          <ImageUpload v-model="form.image"></ImageUpload>
        </el-form-item>
        <el-form-item label="车主" prop="populationId">
          <el-select v-model="form.idCardNumber" placeholder="请选择车主">
            <el-option
              v-for="item in options"
              :key="item.idCardNumber"
              :label="item.name"
              :value="item.idCardNumber">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--车辆一键布控的对话框-->
    <el-dialog title="车辆一键布控" :visible.sync="vehiclesFormVisible" width="60%">
      <el-form :model="vehicles" label-width="100px">
        <!-- 第一行：布防名称和布防时间 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="布防名称" prop="name" required>
              <template slot="label">
                <span class="required-label"></span>
                <span>布防名称</span>
              </template>
              <el-input v-model="vehicles.name" placeholder="请输入任务名称" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 开始时间 -->
            <el-form-item prop="startTime" required>
              <template slot="label">
                <span class="required-label"></span>
                <span>布控时间</span>
              </template>
              <el-date-picker
                v-model="vehicles.startTime"
                type="datetime"
                placeholder="选择开始时间"
                align="right"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>-
              <el-date-picker
                v-model="vehicles.endTime"
                type="datetime"
                placeholder="选择结束时间"
                align="right"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：布防车牌和任务类型 -->
        <el-row>
          <el-col :span="12">
            <el-form-item prop="licensePlate" label="布防车牌" required>
              <template slot="label">
                <span class="required-label"></span>
                <span>布防车牌</span>
              </template>
              <el-input v-model="vehicles.licensePlate" placeholder="布防车牌号" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="type">
              <el-radio v-model="vehicles.taskType" label="1">个人所有</el-radio>
              <el-radio v-model="vehicles.taskType" label="0">社区所有</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：备注 -->
        <el-form-item label="备注" prop="desc">
          <el-input type="textarea" placeholder="请输入内容，长度不超过250个字符" v-model="vehicles.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="vehiclesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="vehiclestForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVehicles, getVehicles, delVehicles, addVehicles, updateVehicles , handleImportVehicles,deployVehicles} from "@/api/community/vehicles";
import ImageUpload from '@/components/ImageUpload'
import { listDistrict } from '@/api/community/district'
import { selPopulation } from '@/api/community/population'
export default {
  name: "Vehicles",
  components: { ImageUpload },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      options:[],
      districtList:[],
      address: '',
      population:[],
      selectedItems:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      //single: true,
      // 非多个禁用
      //multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实有车辆信息表格数据
      vehiclesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      vehiclesFormVisible: false,
      dialogFormVisible:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        licensePlate: null,
        createDate: null,
        status: null,
        populationId: null,
        districtId: null,
        idCardNumber: null,
        max:null,
        min:null
      },
      timeRange: [], // 用于绑定时间范围选择器
      // 车辆一键布控 表单
      vehicles:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        licensePlate: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    var id = this.$route.params.id
    if (id != null && id != undefined && id !== '') {
      localStorage.setItem('districtId', id);
    }
    this.getList();
    this.getPopulationSelect();
    this.getDistrictList();
  },
  methods: {
    handleTimeChange(value) {
      if (value) {
        // 当用户选择了时间范围时，更新vehicles对象
        this.vehicles.startTime = value[0]; // 起始时间
        this.vehicles.endTime = value[1]; // 结束时间
      }
    },
    // 一键布控
    handleControl(item) {
      this.vehicles = {};
      this.vehiclesFormVisible=true;
      // 获取到ite中的车牌号
      this.vehicles.licensePlate = item.licensePlate;
    },
    // 车辆一键布控 确认
    vehiclestForm(){
      deployVehicles(this.vehicles).then(response => {
        this.$modal.msgSuccess("布控成功");
        this.vehiclesFormVisible = false;
      })
    },
    // 跳转一车一档车辆档案详情页面
    redirectToVechiclesPage(item) {
      this.$router.push({
        path: '/vehicles/document/' + item,
        name: 'Build',
        params: {
          item: item
        }
      })
    },
    // 车主下拉框查询
    getPopulationSelect() {
      this.loading = true;
      var districtId = localStorage.getItem('districtId')
      selPopulation(districtId).then(response => {
        this.options = response.data;
        console.log('this.options',this.options);
      });
    },
    /** 查询实有小区统计列表 */
    getDistrictList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.id = item
      listDistrict(this.queryParams).then(response => {
        this.districtList = response.rows;
        console.log('response.rows',response.rows)
        this.loading = false;
      });
    },
    redirectToPopulationPage(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    // 多选框选中数据
    handleSelectionChange(id) {
      if (this.selectedItems.includes(id)) {
        // 如果选中项中包含当前 id，则从 ids 中添加该 id
        if (!this.ids.includes(id)) {
          this.ids.push(id);
        }
      } else {
        // 如果选中项中不包含当前 id，则从 ids 中移除该 id
        const index = this.ids.indexOf(id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
      }
    },
    /** 查询实有车辆信息列表 */
    getList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.districtId = item
      listVehicles(this.queryParams).then(response => {
        console.log('response', response)
        this.vehiclesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        licensePlate: null,
        createDate: null,
        image:null,
        status: null,
        populationId: null,
        idCardNumber: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
/*     // 户主下拉框查询
    getPopulation(){
      getlistPopulation().then(res=>{
        this.population=res.data
      })
    }, */
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实有车辆信息";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      if (this.ids.length === 1) {
        const id = this.ids[0];
        /* this.$message.info("开始修改操作，id：" + id); */
        getVehicles(id).then(response => {
          this.form = response.data;
          console.log('response.data1',this.form);
          this.open = true;
          this.title = "修改实有车辆信息";
        });
      } else if (this.ids.length > 1) {
        this.$message.warning("每次只能修改一个车辆信息统计，请选择单个项目进行修改。");
      } else {
        this.$message.warning("请选择一个车辆信息统计项目进行修改。");
      }
    },
    /** 提交按钮 */
    submitForm() {
      var item = localStorage.getItem('districtId')
      this.form.districtId = item
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVehicles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVehicles(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDistrictList();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      // 判断是否选中
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要删除的数据");
        return;
      }
      const ids = this.ids;
      this.$modal.confirm('是否确认删除实有车辆信息编号为"' + ids + '"的数据项？').then(function() {
        return delVehicles(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.ids=[]
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('community/vehicles/export', {
        ...this.queryParams
      }, `vehicles_${new Date().getTime()}.xlsx`)
    },

    /** 导入按钮操作 */
    handleImport(event) {
      const file = event.target.files[0]; // 获取上传的文件
      try {
        handleImportVehicles(file).then(res=>{
          if(200===res.code){
            this.$modal.msgSuccess("导入成功");
            this.getList()
          }
        });
      } catch (error) {
        console.error('导入失败：', error);
      }
    },
    // 查询小区 实有人口
    handlePopulationClick(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有房屋
    handleEstateClick(id) {
      this.$router.push({
        path: '/community/estate/' + id,
        name: 'Estate',
        params: {
          id: id
        }
      })
    },

    // 查询小区 实有单位
    handleUnitClick(id) {
      this.$router.push({
        path: '/community/unit/' + id,
        name: 'Unit',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有车辆
    handleVehiclesClick(id) {
      this.$router.push({
        path: '/community/vehicles/' + id,
        name: 'Vehicles',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有设备
    handleFacilitiesClick(id) {
      this.$router.push({
        path: '/community/facilities/' + id,
        name: 'Facilities',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有力量
    handleCacheClick() {
      alert('待开发');
    },
  }
};
</script>
<style scoped>
.fixed-image-size1{
  width: 100px; /* 设置容器宽度 */
  height: 100px; /* 设置容器高度 */
  object-fit: cover; /* 保持比例并填充容器 */
}
.required-label {
  color: red;
  margin-right: 4px; /* 与文本标签保持一定间隔 */
}
.product-content1 {
  text-align: center; /* 图片和信息居中对齐 */
  margin-bottom: 20px; /* 底部间距 */
}

.product-content1 .fixed-image-eatate-size {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 500px; /* 高度自适应，保持比例 */
  width: 500px; /* 固定宽度，可以根据需要调整 */
}

#box {
  display: flex;
  justify-content: center; /* 居中显示 */
}

.population-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  margin: 0;
  list-style: none;
}
.product-item {
  width: calc(33.33% - 20px); /* 计算每个项目的宽度，减去外边距 */
  margin: 10px; /* 外边距 */
}

.product-content2 {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 10px;
  border: 1px solid #ccc;
  width: 100%; /* 确保每个项目占据父容器的宽度 */
}

.product-content2 .fixed-image-size3 {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 200px; /* 高度自适应，保持比例 */
  width: auto; /* 固定宽度，可以根据需要调整 */
}

.info {
  flex: 1; /* 让信息部分占据剩余空间 */
}

.info h4,
.info p {
  margin: 0;
}

.additional-info1 {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三列布局 */
  grid-gap: 10px; /* 设置网格之间的间距 */
}

.additional-info1 p {
  margin: 0;
}
</style>
